package main

import (
	"fmt"
	"gitee.com/go-wena/wena/internal/dep"
	"os"

	"gitee.com/go-wena/cli"
	"gitee.com/go-wena/wena"
	"gitee.com/go-wena/wena/utils/spiner"
)

func init() {
	depsCheck()
}

func depsCheck() {
	cli.New(
		cli.Use("dep", "deps"),
		cli.Comment("依赖管理"),
		cli.SubCommand(goDownload(), goVersion(), goEnv(), goNewestVersion()),
	).AddTo(root)
}

func goDownload() *cli.Command {
	return cli.New(
		cli.Use("download"),
		cli.Comment("下载依赖的go sdk"),
		cli.Flags(func(fs *cli.FlagSet) {
			fs.BoolP("force", "f", false, "")
		}),
		cli.Run(func(c *cli.Command, args []string) {
			force, _ := c.Flags().GetBool("force")
			sp := spiner.New(func(s string, args ...interface{}) {
				fmt.Printf(s, args...)
			})
			err := wena.GoDownload(c.Context(), force, func(cur, total, pct int64) {
				sp.PrintProgress(int(pct), "", "")
			})
			cli.CheckExit(err)
		}),
	)
}

func goVersion() *cli.Command {
	return cli.New(
		cli.Use("version"),
		cli.Comment("依赖的go版本"),
		cli.Run(func(c *cli.Command, args []string) {
			cli.CheckExit(wena.PrintGoVersion(c.Context(), os.Stdout))
		}),
	)
}

func goEnv() *cli.Command {
	return cli.New(
		cli.Use("env"),
		cli.Comment("打印go环境变量"),
		cli.Run(func(c *cli.Command, args []string) {
			cli.CheckExit(wena.PrintGoEnv(c.Context(), os.Stdout))
		}),
	)
}

func goNewestVersion() *cli.Command {
	return cli.New(
		cli.Use("newest"),
		cli.Comment("依赖的go版本"),
		cli.Run(func(c *cli.Command, args []string) {
			c.Println("go:")
			f, err := dep.GetNewestGoVersion(c.Context())
			if err != nil {
				c.Println(err.Error())
			} else {
				c.Println(f.Version, f.Os, f.Arch)
			}
			c.Println("upx:")
			u, err := dep.GetNewestUpxVersion(c.Context())
			if err != nil {
				c.Println(err.Error())
			} else {
				c.Println(u.Name)
			}
		}),
	)
}
